﻿using System.Windows.Data;
using System.Windows.Input;
using Zuehlke.Blueprint.Quickstart.Architecture.Presentation.Services.Interfaces.Customers;

namespace Zuehlke.Blueprint.Quickstart.Architecture.Presentation.UserInterface.Views
{
    /// <summary>
    /// ViewModel for the customer view.
    /// </summary>
    public class CustomersViewModel
    {
        #region Private Members

        private string _searchText = string.Empty;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomersViewModel"/> class.
        /// </summary>
        public CustomersViewModel(ICustomerService customerService)
        {
            CustomerServiceInfo = customerService.Info;

            LoadCustomersCommand = customerService.StartLoadingCustomersCommand;
            CancelLoadCustomersCommand = customerService.CancelLoadingCustomersCommand;
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the load customers command.
        /// </summary>
        public ICommand LoadCustomersCommand { get; private set; }

        /// <summary>
        /// Gets the cancel load customers command.
        /// </summary>
        public ICommand CancelLoadCustomersCommand { get; private set; }

        /// <summary>
        /// Gets the customer service info.
        /// </summary>
        public ICustomerServiceInfo CustomerServiceInfo { get; private set; }

        /// <summary>
        /// Gets or sets the search text (and triggers the filering).
        /// </summary>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                UpdateFilter();
            }
        }

        #endregion

        #region Private Helpers

        private void UpdateFilter()
        {
            var collectionView = CollectionViewSource.GetDefaultView(CustomerServiceInfo.Customers);
            if (collectionView.Filter == null)
            {
                collectionView.Filter = FilterPredicate;
            }
            else
            {
                collectionView.Refresh();
            }
        }

        private bool FilterPredicate(object item)
        {
            var customer = item as ICustomer;
            if(customer == null)
            {
                return false;
            }

            var searchText = _searchText.ToLower();
            return (customer.FirstName.ToLower().Contains(searchText) || customer.LastName.ToLower().Contains(searchText));
        }

        #endregion
    }
}
